﻿using System.Text;

namespace DimensionsHelper.LanguageService.Syntax;

public static partial class NodeConverter
{
    public static StringLiteral ToString(SyntaxNode node, SyntaxNode? parent)
    {
        StringLiteral literal = new(parent);
        literal.UpdateFrom(node);
        return literal;
    }


    public static StringLiteral ToString(Expression expression, SyntaxNode? parent)
    {
        if (expression.Is<StringLiteral>(out StringLiteral? strLiteral))
        {
            return strLiteral;
        }

        StringLiteral literal = new(parent);
        literal.UpdateFrom(expression);
        return literal;
    }


    public static StringLiteral CombineAsString<T>(IEnumerable<T> nodes) where T : ITextNode
    {
        if (!nodes.Any())
        {
            return StringLiteral.Default;
        }

        StringBuilder str = new();
        bool isFirst = true;
        ITextNode? last = null;
        int start = 0;

        foreach (T node in nodes)
        {
            if (isFirst)
            {
                start = node.Start;
                isFirst = false;
            }

            if (last != null && node.Start - last.End >= 1)
            {
                str.Append(' ');
            }

            str.Append(node.Text);
            last = node;
        }

        StringLiteral literal = new(null);
        literal.Update(start, last!.End, str.ToString());
        return literal;
    }
}